<template>
  <div id="app">
    <Header :style="HeaderStyle" />
    <el-container class="main-container">
      <CourseLessonNav
        v-if="showSidebar"
        class="sidebar"
        :current-course-id="currentCourseId"
        :current-lesson-id="currentLessonId"
      />
      <el-main
        :class="['content', { centered: !showSidebar }]"
        :style="showSidebar ? 'height:calc(100vh - 60px);overflow-y: auto;overflow-x: hidden;' : ''"
      >
        <router-view :key="$route.fullPath" />
      </el-main>
    </el-container>
    <WordLookup />
    <el-backtop :right="100" :bottom="100" v-if="isWideScreen()" />
  </div>
</template>

<script>
import Header from './components/layout/Header.vue'
import CourseLessonNav from './components/courses/CourseLessonNav.vue'
import { ElContainer, ElMain, ElBacktop } from 'element-plus'
import http from '@/utils/http'
import { setAuthHeader } from '@/utils/auth'
import WordLookup from '@/components/WordLookup.vue'

export default {
  name: 'App',
  components: {
    Header,
    CourseLessonNav,
    ElContainer,
    ElMain,
    ElBacktop,
    WordLookup
  },
  data() {
    return {
      requireLeftBar: false,
      HeaderStyle: 'default',
      currentCourseId: null,
      currentLessonId: null,
      coursePathMap: {} // Map course paths to course IDs
    }
  },
  computed: {
    showSidebar() {
      // Show sidebar on all pages except home
      // const noLeftSidebar = ['PhoneticSymbol', 'Home', 'Grammar',
      //   'Login', 'LearningStatistics', 'VocabularyBook',
      //   'VocabularySearch', 'Dashboard', 'UserManagement', 'PhonicsAlphabet', 'PhonicsLesson'];
      // const showSidebar = noLeftSidebar.includes(this.$route.name);
      // this.HeaderStyle = showSidebar ? 'default' : 'large';
      // return !showSidebar;
      this.HeaderStyle = !this.requireLeftBar ? 'default' : 'large'
      return this.requireLeftBar
    }
  },
  async mounted() {
    // 设置认证头
    setAuthHeader(http)

    // Preload course data to build the path map
    await this.preloadCourseData()
    this.getPathsFromUrl()
  },
  watch: {
    $route: {
      handler(to) {
        // Extract course and lesson IDs from route
        this.extractRouteParams(to)
        this.requireLeftBar = to.meta.requireLeftBar === true
      },
      immediate: true
    }
  },
  methods: {
    getPathsFromUrl() {
      this.currentCourseId = -1
      this.currentLessonId = -1
      const url = window.location.href
      const urlComponents = url.split('/')
      if (urlComponents.length < 2) {
        return
      }
      for (let i = 0; i < urlComponents.length; i++) {
        if (urlComponents[i].indexOf('%') > -1) {
          urlComponents[i] = decodeURIComponent(urlComponents[i])
        }
      }
      let regex = /([\u4e00-\u9fa5]+)\/(\d+)/g // 两个捕获组：中文部分和数字部分
      let match
      let matched1 = false
      // 循环匹配所有符合条件的子串
      while ((match = regex.exec(urlComponents.join('/'))) !== null) {
        const chinese = match[1] // 第一个捕获组：中文部分
        this.currentCourseId = this.coursePathMap[chinese]
        const number = match[2] // 第二个捕获组：数字部分
        this.currentLessonId = number
        matched1 = true
        break
      }
      if (!matched1) {
        let regex = /course\/(\d+)\?/g // 两个捕获组：中文部分和数字部分
        let match
        // 循环匹配所有符合条件的子串
        while ((match = regex.exec(urlComponents.join('/'))) !== null) {
          const courseIdx = match[1] // 第一个捕获组：课程ID
          this.currentCourseId = courseIdx
          break
        }
      }
    },
    isWideScreen() {
      return window.innerWidth >= 768
    },
    async preloadCourseData() {
      try {
        // Load all courses to build a map of course paths to IDs
        const courses = await http.get('/courses')
        // Build map of course paths to IDs
        courses.forEach((cat) => {
          cat.courses.forEach((course) => {
            this.coursePathMap[course.path] = course.id
          })
        })
      } catch (error) {
        console.error('Failed to preload course data:', error)
      }
    },

    extractRouteParams(route) {
      this.getPathsFromUrl()
      // Extract course and lesson info from route
      if (route.params) {
        if (
          route.name &&
          (route.name.includes('Lesson') ||
            route.name.includes('lesson') ||
            route.name.includes('Study') ||
            route.name.includes('study') ||
            route.name.includes('Practice') ||
            route.name.includes('practice') ||
            route.name.includes('Recall') ||
            route.name.includes('recall')) &&
          route.params.id
        ) {
          this.currentLessonId = route.params.id

          // Map course path to course ID
          if (route.params.coursePath && this.coursePathMap[route.params.coursePath]) {
            this.currentCourseId = this.coursePathMap[route.params.coursePath]
          }
        } else if (route.name && (route.name.includes('Course') || route.name.includes('course')) && route.params.id) {
          // For course detail pages
          this.currentCourseId = route.params.id
        }
      }
    }
  }
}
</script>

<style lang="scss">
//导入 '~@/assets/styles/variables.scss';
@use 'assets/styles/global.scss';
@use 'assets/styles/variables.scss';

#app {
  font-family: sans-serif, Avenir, Helvetica, Arial;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  min-height: 100vh;
}

.main-container {
  display: flex;
  flex: 1;
  min-height: calc(100vh - 70px); // Subtract header height
}

.sidebar {
  width: 300px;
  border-right: 1px solid #e6e6e6;
}

.content {
  flex: 1;
  padding: 10px 0px !important;
  transition: all 0.3s ease;
}

.content.centered {
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
  padding: 0;
  // 左右两侧边框宽度为1px
  border-left: 1px solid #f6f6f6;
  border-right: 1px solid #f6f6f6;
}

main {
  max-width: none;
  margin: 0;
  padding: 0;
}

// 定义变量--fullscreen-background-color
:root {
  --fullscreen-background-color: white;
}

:not(:root):fullscreen::backdrop {
  position: fixed;
  inset: 0px;
  background: var(--fullscreen-background-color);
}

@media (max-width: 768px) {
  .sidebar {
    width: 250px;
  }

  .content {
    padding: 0px !important;
  }
}
</style>